package net.lab1024.sa.admin.module.workflow.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.lab1024.sa.admin.module.workflow.domain.vo.WfDetailVo;
import net.lab1024.sa.admin.module.workflow.service.WfProcessService;
import net.lab1024.sa.admin.util.ApplicationContextUtil;
import net.lab1024.sa.base.common.code.WorkFlowErrorCode;
import net.lab1024.sa.base.common.domain.ResponseDTO;
import net.lab1024.sa.base.common.domain.WorkFlowBusinessBo;
import net.lab1024.sa.base.common.service.WorkFlowCommonService;
import org.springframework.aop.framework.AopProxyUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Map;

/**
 * 工作流提交相关接口
 */
@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/workflow/business")
public class WfBusinessController {


    @Resource
    private WfProcessService processService;

    /**
     * 取消流程
     */
    @PostMapping(value = "/save")
    public ResponseDTO<Object> save(@Validated @RequestBody WorkFlowBusinessBo bo) {
        WorkFlowCommonService<Object> workFlowCommonService = ApplicationContextUtil.getBean(bo.getServicePath(), WorkFlowCommonService.class);
        if (ObjectUtil.isEmpty(workFlowCommonService)) {
            return ResponseDTO.error(WorkFlowErrorCode.PARAM_ERROR, "未找到对应的服务");
        }
        Object result = workFlowCommonService.save(BeanUtil.toBean(bo.getFormData(), ApplicationContextUtil.getClazz(workFlowCommonService)));
        return ResponseDTO.ok(result);
    }


    /**
     * 提交流程
     */
    @PostMapping(value = "/commit")
    public ResponseDTO<Object> commit(@Validated @RequestBody WorkFlowBusinessBo bo) {
        WorkFlowCommonService<Object> workFlowCommonService = ApplicationContextUtil.getBean(bo.getServicePath(), WorkFlowCommonService.class);
        if (ObjectUtil.isEmpty(workFlowCommonService)) {
            return ResponseDTO.error(WorkFlowErrorCode.PARAM_ERROR, "未找到对应的服务");
        }
        Object result = workFlowCommonService.commit(bo, BeanUtil.toBean(bo.getFormData(), ApplicationContextUtil.getClazz(workFlowCommonService)));
        return ResponseDTO.ok(result);
    }

    @PostMapping(value = "/preview")

    public ResponseDTO<Map> preview(@Validated @RequestBody WorkFlowBusinessBo bo) {
        return ResponseDTO.ok(processService.preview(bo));
    }



}
